//
//  EventDetailsViewerViewController.m
//  SecretRoom
//
//  Created by Sitdhibhong Laokok on 9/5/54 BE.
//  Copyright 2554 App Tree. All rights reserved.
//

#import <QuartzCore/QuartzCore.h>

#import "EventDetailsViewerViewController.h"

@interface EventDetailsViewerViewController ()
- (void)mapSetup;
- (void)removeEventFromDeviceWithEvent:(Event *)event;
@end

@implementation EventDetailsViewerViewController

@synthesize context;
@synthesize eventLocationMap;
@synthesize eventForDetailsDisplayInformation;
@synthesize placeAnnotation;
@synthesize actionProposeButton;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.title = @"Event Details";
    
    [self mapSetup];
    
    self.eventLocationMap.delegate = self;
    self.toolbarItems = [NSArray arrayWithObjects:flexibleBarButton, self.actionProposeButton, nil];
}

- (void)viewDidUnload
{
    [self setEventForDetailsDisplayInformation:nil];
    [self setContext:nil];
    [self setEventLocationMap:nil];
    [self setPlaceAnnotation:nil];
    [self setActionProposeButton:nil];
    [flexibleBarButton release];
    flexibleBarButton = nil;
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.eventLocationMap addAnnotation:self.placeAnnotation];
    [self clearsSelectionOnViewWillAppear];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger numberOfRow = 0;
    if (section == 0) {
        numberOfRow = 3;
    } else if (section == 1) {
        numberOfRow = 1;
    } else if (section == 2) {
        numberOfRow = 3;
    }
    
    return numberOfRow;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:CellIdentifier] autorelease];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    // Configure the cell...
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cellHeader"] autorelease];
            
            cell.textLabel.text = self.eventForDetailsDisplayInformation.eventName;
            cell.textLabel.textAlignment = UITextAlignmentCenter;
            cell.textLabel.textColor = [UIColor blueColor];
            
        } else if (indexPath.row == 1) {
            NSDate *d = [SLCommonsDateUtility GMTDateToLocalDate:self.eventForDetailsDisplayInformation.eventTimestamp];
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"dd/MM/yyyy HH:mm";
            
            cell.textLabel.text = @"Datetime";
            cell.detailTextLabel.text = [NSString stringWithFormat:@"%@", [formatter stringFromDate:d]];
            
            [formatter release];
            
        } else if (indexPath.row == 2) {
            cell.textLabel.text = @"Note";
            cell.detailTextLabel.text = self.eventForDetailsDisplayInformation.note;
        }
    } else if (indexPath.section == 1) {
        [cell addSubview:self.eventLocationMap];
    } else if (indexPath.section == 2) {
        if (indexPath.row == 0) {
            cell.textLabel.text = @"People";
            cell.detailTextLabel.text = @"A, B, C";
        } else if (indexPath.row == 1) {
            cell.textLabel.text = @"Tags";
            cell.detailTextLabel.text = @"a,b,c";
        } else if (indexPath.row == 2) {
            cell.textLabel.text = @"Collection";
            cell.detailTextLabel.text = [NSString stringWithFormat:@"%i", [self.eventForDetailsDisplayInformation.evidences count]];
        }
    }
    
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat heightForRow = 44.0;
    
    if (indexPath.section == 0) {
        if (indexPath.row == 2) {
            heightForRow = 150.0;
        }
    } else if (indexPath.section == 1) {
        heightForRow = 150.0;
    } 
    
    return heightForRow;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView cellForRowAtIndexPath:indexPath].selected = NO;
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.eventForDetailsDisplayInformation.permanentLink]];
        }
    }
}

- (void)mapSetup
{
    locationPoint = CLLocationCoordinate2DMake([self.eventForDetailsDisplayInformation.latitude floatValue], [self.eventForDetailsDisplayInformation.longitude floatValue]);
    
    self.placeAnnotation = [EventLocationAnnotation eventLocationAnnotationWithCoordinate:locationPoint name:self.eventForDetailsDisplayInformation.eventName detail:self.eventForDetailsDisplayInformation.note];
    
    MKCoordinateSpan span;
    span.latitudeDelta = 0.005;
    span.longitudeDelta = 0.005;
    
    MKCoordinateRegion region;
    region.span = span;
    region.center = self.placeAnnotation.coordinate;
    
    self.eventLocationMap.showsUserLocation = NO;
    self.eventLocationMap.frame = CGRectMake(10, 2, 300, 150);
    self.eventLocationMap.layer.cornerRadius = 10;
    
    self.eventLocationMap.region = region;
}

- (void)dealloc {
    [eventForDetailsDisplayInformation release];
    [context release];
    [eventLocationMap release];
    [placeAnnotation release];
    [actionProposeButton release];
    [flexibleBarButton release];
    [super dealloc];
}

- (IBAction)actionProposeButtonClicked:(id)sender 
{
    UIActionSheet *proposeActionOptions = [[[UIActionSheet alloc] initWithTitle:self.eventForDetailsDisplayInformation.eventName delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:@"Delete" otherButtonTitles:@"Archive", nil] autorelease];
    [proposeActionOptions showFromToolbar:self.navigationController.toolbar];
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (actionSheet.cancelButtonIndex == buttonIndex) {
        NSLog(@"Cancel");
    } else if (actionSheet.destructiveButtonIndex == buttonIndex) {
        NSLog(@"Delete");
        UIAlertView *deletConfirmation = [[UIAlertView alloc] initWithTitle:self.eventForDetailsDisplayInformation.eventName message:@"All data of this event will be removed. Do you want to remove ?" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"YES", nil];
        
        deletConfirmation.tag = 100;
        [deletConfirmation show];
        [deletConfirmation release];
        
    } else if (buttonIndex == 1) {
        NSLog(@"Archive Event");
        UIAlertView *archivedConfirmation = [[UIAlertView alloc] initWithTitle:self.eventForDetailsDisplayInformation.eventName message:[NSString stringWithFormat:@"'%@' will be remvoe to Log Book", self.eventForDetailsDisplayInformation.eventName] delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
        
        archivedConfirmation.tag = 200;
        [archivedConfirmation show];
        [archivedConfirmation release];
    }

}

#pragma mark - MKMapViewDelegate
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
    EventLocationAnnotation *annotate = (EventLocationAnnotation *)annotation;
    MKPinAnnotationView *annotationView = [[[MKPinAnnotationView alloc] initWithAnnotation:annotate reuseIdentifier:annotate.name] autorelease];
    
    annotationView.animatesDrop = YES;
    annotationView.canShowCallout = YES;
    
    return annotationView;
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 100) {
        if (alertView.cancelButtonIndex != buttonIndex) {
            NSLog(@"Let's perform delete archive");
            [self performSelectorOnMainThread:@selector(removeEventFromDeviceWithEvent:) withObject:self.eventForDetailsDisplayInformation waitUntilDone:YES];
            
            [self.navigationController popViewControllerAnimated:YES];
        }
    } else if (alertView.tag == 200) {
        if (alertView.cancelButtonIndex != buttonIndex) {
            NSLog(@"Mark this event to Log Book");
            self.eventForDetailsDisplayInformation.isArchived = [NSNumber numberWithBool:YES];
                        
            NSError *error = nil;
            [[[SRConnectionControlCenter sharedInstance] manageObjectContext] save:&error];
            if (error != nil) {
                NSLog(@"Error : %@", [error localizedDescription]);
            }
            
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
}

- (void)removeEventFromDeviceWithEvent:(Event *)eventToDelete
{
//    NSLog(@"remove event %@", eventToDelete);
    [[[SRConnectionControlCenter sharedInstance] manageObjectContext] deleteObject:self.eventForDetailsDisplayInformation];
    NSError *error = nil;
    [[[SRConnectionControlCenter sharedInstance] manageObjectContext] save:&error];
    
    if (error != nil) {
        NSLog(@"Error while delete: %@", [error localizedDescription]);
    }
}

@end
